<?php
/**
 * Formulaire de connexion
 */
require_once("include/setup.php");
require_once(CLASS_PATH.'user.class.php');

$error = false;
$data = $_POST['login'];

if (isset($_REQUEST['logout'])) {
	LoginHelper::disconnectUser();
	$url = RACINE_URL;
	if (isset($data['redirect_url'])) {
		$url = $data['redirect_url'];
	}
	WebsiteHelper::redirect($url);
}

if (LoginHelper::isConnected()) {
	WebsiteHelper::redirect(RACINE_URL);
}

$login = array(
	'email' => '',
	'redirect_url' => $_SESSION['login_redirect_url']
);

if (isset($_POST['login'])) {
	
	$email = $data['email'];
	$cryptedPassword = User::cryptSendedPassword($data['password']);
	
	$user = User::getUser(array(
		'email' => $email
	));
	
	if (empty($user) || $user->password_hash != $cryptedPassword) {
		Notification::add(Notification::$ERROR, "E-mail ou mot de passe incorrect");
		$error = true;
	}
	else if (!empty($user) && $user->type_droits_user == 0) {
		$_SESSION['validation_id_user'] = $user->id_user;
		WebsiteHelper::redirect('inscription.validation.php');		
	}
	if (!$error) {
		LoginHelper::connectUser($user);
		WebsiteHelper::redirect($data['redirect_url']);
	}
	$login = array(
		'email' => $data['email'],
		'redirect_url' => $data['redirect_url']
	);
}

$v = new JapwordView();
$v->addNotifications();
$v->assign('login', $login);
$v->assign('nologinbar', true);
$v->display('login.html');
?>